package com.chrilwe.pigpig.filesystem.common.balance;

import java.util.ArrayList;
import java.util.List;

/**
  * 轮询算法
 * @author chrilwe
 * @date 2020-10-3
 */
public class RoundRobinBalance {
	
	//静态权重比总和
	private int staticWeightSum;
	
	private List<VideoServer> videoServers;
	
	public RoundRobinBalance(List<VideoServer> videoServers) {
		if(videoServers == null || videoServers.size() == 0) {
			throw new RuntimeException("videoServer null or size = 0");
		}
		this.videoServers = videoServers;
		for (VideoServer videoServer : videoServers) {
			staticWeightSum += videoServer.getStaticWeight();
		}
	}
	
	public VideoServer getVideoServer() {
		//动态权重比=动态权重比+静态权重比
		for (VideoServer videoServer : videoServers) {
			int staticWeight = videoServer.getStaticWeight();
			int dynamicsWeight = videoServer.getDynamicsWeight() + staticWeight;
		    videoServer.setDynamicsWeight(dynamicsWeight);
		}
		
		//获取最大的动态权重返回
		int maxIndex = 0;
		int max = 0;
		for(int i = 0; i < videoServers.size(); i++) {
			int dynamicsWeight = videoServers.get(i).getDynamicsWeight();
			if(dynamicsWeight > max) {
				max = dynamicsWeight;
				maxIndex = i;
			}
		}
		
		//将最大动态权重，减去staticWeightSum
		int v = max - staticWeightSum;
		VideoServer videoServer = videoServers.get(maxIndex);
		videoServer.setDynamicsWeight(v);
		videoServers.set(maxIndex, videoServer);
		return videoServer;
	}
}
